//
//  DynamicReplyVC.m
//  TuYouAPP
//
//  Created by L on 14-2-24.
//
//

#import "DynamicReplyVC.h"
#import "DynamicReplayCell.h"
#import "DataModel.h"
#import "HisInfoVC.h"
#import "ShareView.h"
#import "UIButton+WebCache.h"
#import "Util.h"
#import <ShareSDK/ShareSDK.h>
#import <AVOSCloud/AVOSCloud.h>
#import "MyPublishVC.h"
#import "LoginVC.h"
@interface DynamicReplyVC ()
{
    MWPhotoBrowser *browser;
    UIView *inputView;
    UITapGestureRecognizer *gesture;
    UITextField *inputText;
    ShareView *shareView;
    NSMutableArray *replyArray;
    UILabel *coutlabel;
    BOOL isHaveTagUser;
    NSString *TagNameStr;
    TYCommment *tempComment;
    UILabel *loadMoreLabel;
    UIActivityIndicatorView *refresh;
    NSDate *lastTime;
    NSDate *firstTime;

}
@end
@implementation DynamicReplyVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)getReplay
{
    [refresh startAnimating];
    [self.thePublish getCommentByTime:firstTime bback:YES callback:^(NSArray *arr, NSString *err) {
         [self.slimeView endRefresh];
        [refresh stopAnimating];
        if (arr&&!err) {
            if (arr.count ==0) {
                [self.tableview reloadData];
                self.refreshLabel.text = self.textNoMore;

                return ;
            }
            TYCommment *state = [arr firstObject];
            firstTime = state.mTimeC;
            state = [arr lastObject];
            lastTime = state.mTimeC;

            [replyArray addObjectsFromArray:arr];
            [self.tableview reloadData];
            
            if (arr.count<ONE_PAGE) {
                self.refreshLabel.text = self.textNoMore;
            }
            else
            {
                self.refreshLabel.text = self.textPull;
                
            }
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"获取评论失败"];
        }
    }];
//    [self.thePublish getComment:1 callback:^(NSArray *arr, NSString *err) {
//        [refresh stopAnimating];
//        if (arr&&!err) {
//            [replyArray addObjectsFromArray:arr];
//            [self.tableview reloadData];
//        }
//        else
//        {
//            [SVProgressHUD showErrorWithStatus:@"获取评论失败"];
//        }
//    }];
}
-(void)loadNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeContentViewPoint:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)  name:UIKeyboardWillHideNotification object:nil];

}
- (void)viewDidLoad
{
    [self loadNotification];
    isHaveTagUser = NO;
    self.mPageName = @"动态详情";
    [super viewDidLoad];
    replyArray = [[NSMutableArray alloc]init];
    
    
    [self getReplay];
    gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backgroundTaped:)];
    
    
    self.LeftBarTitle = @"返回";
    self.RightBarTitle = @"分享";
    self.Title = @"动态详情";
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.haveFullupRefreshView = YES;
    [self initWithRefreshTableViewIos7:CGRectMake(0, 64, 320, DEVICE_Height-64) Ios6rect:CGRectMake(0, 44, 320, DEVICE_Height-64)];
    
    self.tableview.backgroundColor = ColorRGB(230,230, 230);
    self.tableview.separatorStyle = UITableViewCellSelectionStyleNone;
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
    headerView.backgroundColor = [UIColor clearColor];
 
    
    UIView *headTop = [[UIView alloc]initWithFrame:CGRectMake(9, 10, 302, 51)];
    
    headTop.backgroundColor = [UIColor whiteColor];
    headTop.layer.borderWidth = 0.5;
    headTop.layer.borderColor = [ColorRGB(212, 212, 212)CGColor];
    
    [headerView addSubview:headTop];

    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(14, 15, 40, 40)];
    [btn addTarget:self action:@selector(headBtnTouched:) forControlEvents:UIControlEventTouchUpInside];
  //  [btn setImage:[UIImage imageNamed:@"headimage.jpeg"] forState:UIControlStateNormal];
    [btn setBackgroundImageWithURL:[NSURL URLWithString:self.thePublish.mTaguser.mHeadImgURL ] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"70_70.png"]];
    [headerView addSubview:btn];
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(61, 13,280, 21)];
    nameLabel.backgroundColor = [UIColor clearColor];
    nameLabel.font = [UIFont systemFontOfSize:16];
    nameLabel.textColor = ColorRGB(205, 136, 52);
    nameLabel.text = self.thePublish.mTaguser.mUserDisplayName;
    [headerView addSubview:nameLabel];
    CGSize constraint = CGSizeMake(280, CGFLOAT_MAX);
    CGSize size = [self.thePublish.mTaguser.mUserDisplayName sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
    
    UIImageView *seximage = [[UIImageView alloc]initWithFrame:CGRectMake(65+size.width+5, 18, 12, 12)];
    seximage.image = self.thePublish.mTaguser.mSex == 1? [UIImage imageNamed:@"women.png"]:[UIImage imageNamed:@"men.png"];
    [headerView addSubview:seximage];
    UIButton *topbtn = [[UIButton alloc]initWithFrame:CGRectMake(14, 15, 150, 40)];
    topbtn.backgroundColor = [UIColor clearColor];
    [topbtn addTarget:self action:@selector(headBtnTouched:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:topbtn];
    UILabel *addlabel = [[UILabel alloc]initWithFrame:CGRectMake(61, 38, 250, 15)];
    addlabel.font = [UIFont systemFontOfSize:12];
  //  addlabel.text = @"重庆市渝北区";
   // addlabel.text = self.thePublish.mPointInfo;
    addlabel.text = self.thePublish.mTaguser.mUserPointAddr;
    addlabel.backgroundColor = [UIColor clearColor];
    [headerView addSubview:addlabel];
    
    
    
    UIView *botView = [[UIView alloc]initWithFrame:CGRectMake(9, 70, 302, 120)];
    
    botView.backgroundColor = [UIColor whiteColor];
    botView.layer.borderWidth = 0.5;
    botView.layer.borderColor = [ColorRGB(212, 212, 212)CGColor];
    
    [headerView addSubview:botView];
    
    
    UIImageView *locimg = [[UIImageView alloc]initWithFrame:CGRectMake(17, 77, 7, 10)];
    locimg.image = [UIImage imageNamed:@"weizi.png"];
    [headerView addSubview:locimg];
    
    UILabel *arrdLabel = [[UILabel alloc] initWithFrame:CGRectMake(27, 72, 250, 21)];
    arrdLabel.textColor = [UIColor grayColor];
    arrdLabel.font = [UIFont systemFontOfSize:10];
    arrdLabel.text = self.thePublish.mPointInfo;
    arrdLabel.backgroundColor = [UIColor clearColor];
    [headerView addSubview:arrdLabel];

    UILabel *Distance = [[UILabel alloc] initWithFrame:CGRectMake(220, 72, 80, 21)];
    Distance.backgroundColor = [UIColor clearColor];
    Distance.textAlignment = NSTextAlignmentRight;
    Distance.textColor = [UIColor grayColor];
    Distance.font = [UIFont systemFontOfSize:10];
    Distance.text = self.thePublish.mPBetweenInfo;
    [headerView addSubview:Distance];

     constraint = CGSizeMake(295, CGFLOAT_MAX);
     size = [self.thePublish.mContext sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
    
    UILabel *contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 95, 295, size.height+15)];
    
    
    
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc]initWithString:self.thePublish.mContext];
    NSInteger strLength = [self.thePublish.mContext length];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineSpacing:2];
    [attString addAttribute:NSParagraphStyleAttributeName
                      value:style
                      range:NSMakeRange(0, strLength)];
    
    contentLabel.attributedText = attString;
    contentLabel.font = [UIFont systemFontOfSize:16];
    contentLabel.numberOfLines = 0;
    contentLabel.textColor = [UIColor blackColor];
    contentLabel.backgroundColor = [UIColor clearColor];
  //  contentLabel.text =self.thePublish.mContext;
    [headerView addSubview:contentLabel];
    
    float orignY;
    orignY = contentLabel.frame.size.height +contentLabel.frame.origin.y+10;

    if (self.thePublish.mImgArr && self.thePublish.mImgArr.count>0) {
        float btnX = 15;
        for (int i = 0; i<self.thePublish.mImgArr.count; i++) {
            if (btnX>260) {
                btnX = 15;
                orignY+=90;
            }
            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(btnX, orignY, 84, 84)];
            [btn addTarget:self action:@selector(photoTouched:) forControlEvents:UIControlEventTouchUpInside];
            
            NSString *image = [self.thePublish.mImgArr objectAtIndex:i];
           NSURL *url = [NSURL URLWithString: [Util makeSmallImgURL:image]];
            
           [ btn setBackgroundImageWithURL:url forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"160_160.png"]];
         //   [btn setImageWithURL:url forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"1.png"]];
            btn.tag = i+10;
            [headerView addSubview:btn];
            btnX += 90;
        }
        orignY +=80;
    
    }
    else
    {
        orignY -= 10;
    }
   // orignY += 10;
    UILabel *time = [[UILabel alloc]initWithFrame:CGRectMake(17, orignY+10, 200, 21)];
    time.textColor = [UIColor grayColor];
    time.font = [UIFont systemFontOfSize:10];

    time.text = self.thePublish.mTimeText;
    [headerView addSubview:time];
    

    
      UILabel *replyCount = [[UILabel alloc]initWithFrame:CGRectMake(215, orignY+10, 60, 21)];
    replyCount.textColor = [UIColor grayColor];
    replyCount.font = [UIFont systemFontOfSize:14];
    replyCount.textAlignment = NSTextAlignmentRight;

    replyCount.text = @"回复";
    UIImageView *replyImage = [[UIImageView alloc]initWithFrame:CGRectMake(280, orignY+15, 20, 13)];
    replyImage.image = [UIImage imageNamed:@"huifu.png"];
    
    UIButton *huifuBtn = [[UIButton alloc]initWithFrame:CGRectMake(250, orignY+10, 60,30)];
    huifuBtn.backgroundColor = [UIColor clearColor];
    [huifuBtn addTarget:self action:@selector(huifuBtnTouched:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:huifuBtn];
    [headerView addSubview:time];
    [headerView addSubview:replyCount];
    [headerView addSubview:replyImage];
    orignY += 30;

    

    CGRect rect = headerView.frame;
    rect.size.height = orignY+60;
    headerView.frame = rect;
    
    rect = botView.frame;
    rect.size.height = orignY-60 ;
    botView.frame = rect;
    
    UIView * replaycoutView = [[UIView alloc]initWithFrame:CGRectMake(9, botView.frame.origin.y+botView.frame.size.height + 10, 302, 40)];
    replaycoutView.backgroundColor = [UIColor whiteColor];
    
    replaycoutView.layer.borderWidth = 0.5;
    replaycoutView.layer.borderColor = [ColorRGB(212, 212, 212)CGColor];
    
    coutlabel = [[UILabel alloc]initWithFrame:CGRectMake(6, 0, 320, 40)];
    coutlabel.backgroundColor = [UIColor clearColor];
    coutlabel.font = [UIFont systemFontOfSize:14];
    coutlabel.text = self.thePublish.mReBackCount!=0? [NSString stringWithFormat:@"%d条回复",self.thePublish.mReBackCount]:@"暂无回复";
    
    [replaycoutView addSubview:coutlabel];
    
   [headerView addSubview:replaycoutView];
    
    self.tableview.tableHeaderView = headerView;
    
    
    if (SystemIsiOS7()) {
        inputView = [[UIView alloc]initWithFrame:CGRectMake(0, DEVICE_Height-45, 320, 45)];
        
    }
    else
    {
        inputView = [[UIView alloc]initWithFrame:CGRectMake(0, DEVICE_Height-65, 320, 45)];
    }
    UIImageView *bgImg = [[UIImageView alloc]initWithFrame:inputView.bounds];
    bgImg.image = [UIImage imageNamed:@"huifukuang.png"];
    [inputView addSubview:bgImg];
    inputText = [[UITextField alloc]initWithFrame:CGRectMake(24, 10, 215, 25)];
  //  inputText.text = @"";
    inputText.returnKeyType = UIReturnKeySend;
    inputText.placeholder = @"回复";
    inputText.delegate = self;
    [inputView addSubview:inputText];
    
    
    
//    UIButton *sendbtn = [[UIButton alloc]initWithFrame:CGRectMake(260, 5, 55, 35)];
//    [sendbtn setTitle:@"发送" forState:UIControlStateNormal];
//    sendbtn.backgroundColor = [UIColor clearColor];
//    [sendbtn addTarget:self action:@selector(sendBtnTouched:) forControlEvents:UIControlEventTouchUpInside];
//    [inputView addSubview:sendbtn];
    
    
   // UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 45)];
//    UIButton *loadBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
//    [loadBtn addTarget:self action:@selector(taptoAddMore:) forControlEvents:UIControlEventTouchUpInside];
//    loadMoreLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 150, 20)];
//    loadMoreLabel.center = loadBtn.center;
//    loadMoreLabel.text = @"点击加载更多";
//    loadMoreLabel.font = [UIFont systemFontOfSize:12];
//    loadMoreLabel.textAlignment = NSTextAlignmentCenter;
//    
//   refresh = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//    refresh.frame = CGRectMake(20, 5, 20, 20);
//    refresh.hidesWhenStopped = YES;
//    loadBtn.backgroundColor = [UIColor clearColor];
//    [footerView addSubview:loadBtn];
//    [footerView addSubview:loadMoreLabel];
//    [footerView addSubview:refresh];

//footerView.backgroundColor = [UIColor clearColor];
  //  self.tableview.tableFooterView = footerView;
    [self.view addSubview:inputView];
    
    
    
    shareView = [ShareView ShareThisView];
    UIGestureRecognizer *tapges = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(shareViewTouched:)];
    [shareView addGestureRecognizer:tapges];
    
    
    [shareView.Friend addTarget:self action:@selector(pengyouquanBtn:) forControlEvents:UIControlEventTouchUpInside];
        [shareView.Weibo addTarget:self action:@selector(weiboBtn:) forControlEvents:UIControlEventTouchUpInside];
        [shareView.weixinFriend addTarget:self action:@selector(weixinhaoyouBtn:) forControlEvents:UIControlEventTouchUpInside];
        [shareView.Mail addTarget:self action:@selector(tengxunweiboBtn:) forControlEvents:UIControlEventTouchUpInside];
        [shareView.report addTarget:self action:@selector(jubaoBtn:) forControlEvents:UIControlEventTouchUpInside];
        [shareView.cancel addTarget:self action:@selector(quxiaoBtn:) forControlEvents:UIControlEventTouchUpInside];
    


    
}
-(void)taptoAddMore:(UIButton *)sender
{
    [refresh startAnimating];
    [self.thePublish getCommentByTime:lastTime bback:NO callback:^(NSArray *arr, NSString *err) {
        [refresh stopAnimating];
        if (arr&&!err) {
            if (arr.count == 0) {
               // [SVProgressHUD showErrorWithStatus:@"没有更多评论"];
                self.refreshLabel.text = self.textNoMore;
                return ;
            }
            TYCommment *state = [arr firstObject];
        
            firstTime = state.mTimeC;
            state = [arr lastObject];
            lastTime = state.mTimeC;
            
            [replyArray addObjectsFromArray:arr];
            [self.tableview reloadData];
            if (arr.count <10) {
                self.refreshLabel.text = self.textNoMore;

            }
            else
            {
                self.refreshLabel.text = self.textPull;

            }
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"获取评论失败"];
        }
    }];

}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    [self sendBtnTouched:theTextField];
        return YES;
}
-(void)huifuBtnTouched:(UIButton *)sender
{
    isHaveTagUser = NO;
    [inputText becomeFirstResponder];
}
-(void)shareViewTouched:(UIGestureRecognizer*)sender

{
    [inputText resignFirstResponder];
    [UIView animateWithDuration:0.2 animations:^{
        CGRect rect = shareView.frame;
        rect.origin.y = DEVICE_Height;
        shareView.frame = rect;
        
    }];

}
-(void)pengyouquanBtn:(UIButton *)sender
{
    //NSString *imgurl = [Util makeSmallImgURL:[self.thePublish.mImgArr objectAtIndex:0]];
    
    
    NSMutableString *contentStr = [[NSMutableString alloc]initWithString:self.thePublish.mContext];
    // [contentStr appendFormat:@"来自@%@的途友动态,",self.thePublish.mTaguser.mUserDisplayName];
    NSString *urlstr = [NSString stringWithFormat:@"http://app.tuyou.com/dongtai/%@",self.thePublish.objId];

    id<ISSContent> content = [ShareSDK content:contentStr
                                defaultContent:nil
                                         image:[ShareSDK imageWithUrl:[self.thePublish.mImgArr objectAtIndex:0]]
                                         title:contentStr
                                           url:urlstr
                                   description:nil
                                     mediaType:SSPublishContentMediaTypeApp];
    
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                         allowCallback:YES
                                                         authViewStyle:SSAuthViewStyleFullScreenPopup
                                                          viewDelegate:nil
                                               authManagerViewDelegate:nil];
    
    //在授权页面中添加关注官方微博

    
    [ShareSDK shareContent:content
                      type:ShareTypeWeixiTimeline
               authOptions:authOptions
             statusBarTips:YES
                    result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                        
                        NSLog( @"%d",state);
                        if (state == SSPublishContentStateSuccess)
                        {
                               [SVProgressHUD showSuccessWithStatus:@"成功"];
                            NSLog(@"success");
                        }
                        else if (state == SSPublishContentStateCancel)
                        {
                            [SVProgressHUD showSuccessWithStatus:@"成功"];
                        }
                        else if (state == SSPublishContentStateFail)
                        {
                            if ([error errorCode] == -22003)
                            {
                                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TEXT_TIPS", @"提示")
                                                                                    message:[error errorDescription]
                                                                                   delegate:nil
                                                                          cancelButtonTitle:NSLocalizedString(@"TEXT_KNOW", @"知道了")
                                                                          otherButtonTitles:nil];
                                [alertView show];
                            }
                        }
                    }];

}
-(void)weiboBtn:(UIButton *)sender
{
    //id<ISSCAttachment> img;
   // id<ISSContent> content = [content addSinaWeiboUnitWithContent:@"发布微博" image:nil ];
    [GInfo shareClient].isAVOSCloud = NO;
    NSString *acon = [[NSString alloc]initWithString:self.thePublish.mContext];
    NSMutableString* contentStr =[[NSMutableString alloc]init];
    if (acon.length>110) {
       
    [contentStr appendString: [acon substringWithRange:NSMakeRange(0, 110) ]];
    }
    else
    {
        [contentStr appendString:acon];
    }
    [contentStr appendFormat:@"来自@%@ 的途友动态:",self.thePublish.mTaguser.mUserDisplayName];
    NSString *urlstr = [NSString stringWithFormat:@"http://app.tuyou.com/dongtai/%@",self.thePublish.objId];
    [contentStr appendFormat:@"%@",urlstr];
    
    id<ISSContent> content = [ShareSDK content:contentStr
                                defaultContent:nil
                                         image:self.thePublish.mImgArr.count !=0?[ShareSDK imageWithUrl:[self.thePublish.mImgArr objectAtIndex:0]]:nil
                                         title:nil
                                           url:nil
                                   description:nil
                                     mediaType:self.thePublish.mImgArr.count!=0?SSPublishContentMediaTypeImage:SSPublishContentMediaTypeText];
    
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                         allowCallback:YES
                                                         authViewStyle:SSAuthViewStyleFullScreenPopup
                                                          viewDelegate:nil
                                               authManagerViewDelegate:nil];
    
    //在授权页面中添加关注官方微博
    [authOptions setFollowAccounts:[NSDictionary dictionaryWithObjectsAndKeys:
                                    [ShareSDK userFieldWithType:SSUserFieldTypeName value:@"ShareSDK"],
                                    SHARE_TYPE_NUMBER(ShareTypeSinaWeibo),
                                    [ShareSDK userFieldWithType:SSUserFieldTypeName value:@"ShareSDK"],
                                    SHARE_TYPE_NUMBER(ShareTypeTencentWeibo),
                                    nil]];
    
    [ShareSDK shareContent:content
                      type:ShareTypeSinaWeibo
               authOptions:authOptions
             statusBarTips:YES
                    result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                        
                        if (state == SSPublishContentStateSuccess)
                        {
                            [SVProgressHUD showSuccessWithStatus:@"分享成功"];
                            NSLog(@"success");
                        }
                        else if (state == SSPublishContentStateFail)
                        {
                            if ([error errorCode] == -22003)
                            {
                                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TEXT_TIPS", @"提示")
                                                                                    message:[error errorDescription]
                                                                                   delegate:nil
                                                                          cancelButtonTitle:NSLocalizedString(@"TEXT_KNOW", @"知道了")
                                                                          otherButtonTitles:nil];
                                [alertView show];
                            }
                        }
                    }];

   
}


-(void)weixinhaoyouBtn:(UIButton *)sender
{
    NSMutableString *contentStr = [[NSMutableString alloc]initWithString:self.thePublish.mContext];
   // [contentStr appendFormat:@"来自@%@的途友动态,",self.thePublish.mTaguser.mUserDisplayName];
    NSString *urlstr = [NSString stringWithFormat:@"http://app.tuyou.com/dongtai/%@",self.thePublish.objId];
  //  [contentStr appendFormat:@"下载应用:%@",urlstr];
    
    id<ISSContent> content = [ShareSDK content:contentStr
                                defaultContent:nil
                                         image:[ShareSDK imageWithUrl:[self.thePublish.mImgArr objectAtIndex:0]]
                                         title:contentStr
                                           url:urlstr
                                   description:nil
                                     mediaType:SSPublishContentMediaTypeApp];
    
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                         allowCallback:YES
                                                         authViewStyle:SSAuthViewStyleFullScreenPopup
                                                          viewDelegate:nil
                                               authManagerViewDelegate:nil];
    
    //在授权页面中添加关注官方微博
    [authOptions setFollowAccounts:[NSDictionary dictionaryWithObjectsAndKeys:
                                    [ShareSDK userFieldWithType:SSUserFieldTypeName value:@"ShareSDK"],
                                    SHARE_TYPE_NUMBER(ShareTypeSinaWeibo),
                                    [ShareSDK userFieldWithType:SSUserFieldTypeName value:@"ShareSDK"],
                                    SHARE_TYPE_NUMBER(ShareTypeTencentWeibo),
                                    nil]];
    
    [ShareSDK shareContent:content
                      type:ShareTypeWeixiSession
               authOptions:authOptions
             statusBarTips:YES
                    result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                        
                        if (state == SSPublishContentStateSuccess)
                        {
                            [SVProgressHUD showSuccessWithStatus:@"分享成功"];
                            NSLog(@"success");
                        }
                        else if (state == SSPublishContentStateFail)
                        {
                            if ([error errorCode] == -22003)
                            {
                                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TEXT_TIPS", @"提示")
                                                                                    message:[error errorDescription]
                                                                                   delegate:nil
                                                                          cancelButtonTitle:NSLocalizedString(@"TEXT_KNOW", @"知道了")
                                                                          otherButtonTitles:nil];
                                [alertView show];
                            }
                        }
                    }];
}
-(void)tengxunweiboBtn:(UIButton *)sender
{
    
    NSString *acon = [[NSString alloc]initWithString:self.thePublish.mContext];
    NSMutableString* contentStr =[[NSMutableString alloc]init];
    if (acon.length>110) {
        
        [contentStr appendString: [acon substringWithRange:NSMakeRange(0, 110) ]];
    }
    else
    {
        [contentStr appendString:acon];
    }
    [contentStr appendFormat:@"来自@%@的途友动态",self.thePublish.mTaguser.mUserDisplayName];
    NSString *urlstr = [NSString stringWithFormat:@"http://app.tuyou.com/dongtai/%@",self.thePublish.objId];
    [contentStr appendFormat:@":%@",urlstr];

    id<ISSContent> content = [ShareSDK content:contentStr
                                defaultContent:nil
                                         image:[ShareSDK imageWithUrl:[self.thePublish.mImgArr objectAtIndex:0]]
                                         title:nil
                                           url:nil
                                   description:nil
                                     mediaType:self.thePublish.mImgArr.count==0?SSPublishContentMediaTypeText:SSPublishContentMediaTypeImage];
    
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                         allowCallback:YES
                                                         authViewStyle:SSAuthViewStyleFullScreenPopup
                                                          viewDelegate:nil
                                               authManagerViewDelegate:nil];
    
    //在授权页面中添加关注官方微博
    [authOptions setFollowAccounts:[NSDictionary dictionaryWithObjectsAndKeys:
                                    [ShareSDK userFieldWithType:SSUserFieldTypeName value:@"ShareSDK"],
                                    SHARE_TYPE_NUMBER(ShareTypeSinaWeibo),
                                    [ShareSDK userFieldWithType:SSUserFieldTypeName value:@"ShareSDK"],
                                    SHARE_TYPE_NUMBER(ShareTypeTencentWeibo),
                                    nil]];
    
    [ShareSDK shareContent:content
                      type:ShareTypeTencentWeibo
               authOptions:authOptions
             statusBarTips:YES
                    result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                        
                        if (state == SSPublishContentStateSuccess)
                        {
                            [SVProgressHUD showSuccessWithStatus:@"分享成功"];
                            NSLog(@"success");
                        }
                        else if (state == SSPublishContentStateFail)
                        {
                            if ([error errorCode] == -22003)
                            {
                                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TEXT_TIPS", @"提示")
                                                                                    message:[error errorDescription]
                                                                                   delegate:nil
                                                                          cancelButtonTitle:NSLocalizedString(@"TEXT_KNOW", @"知道了")
                                                                          otherButtonTitles:nil];
                                [alertView show];
                            }
                        }
                    }];

}
-(void)jubaoBtn:(UIButton *)sender
{
    
}
-(void)quxiaoBtn:(UIButton *)sender
{
    [UIView animateWithDuration:0.2 animations:^{
        CGRect rect = shareView.frame;
        rect.origin.y = DEVICE_Height;
        shareView.frame = rect;
        
    }];

}


-(void)headBtnTouched:(id)sender
{
    if (self.isFromHis) {
        return;
    }
    MyPublishVC *vc = [[MyPublishVC alloc]init];

    vc.user = self.thePublish.mTaguser;
    vc.fromMyself = NO;
    [self.navigationController pushViewController:vc animated:YES];

}
-(void)sendBtnTouched:(id)sender
{
    if ([TYUser isNeedLogin]) {
        LoginVC *logvc = [[LoginVC alloc]initWithNibName:@"LoginVC" bundle:nil];
        // logvc.tagVC = vc;
        [self.navigationController pushViewController:logvc animated:YES];
        return;
    }
    if (inputText.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"回复内容不能为空"];
        return;
    }
    
    [SVProgressHUD showWithStatus:@"评论中"];

    if ([inputText.text hasPrefix:@"回复@"]) {
        int lentgh = TagNameStr.length+3;
        NSString *astr = [inputText.text substringWithRange:NSMakeRange(lentgh, 1)];
        NSString *content = [inputText.text substringWithRange:NSMakeRange(lentgh+1, inputText.text.length - (lentgh+1))];
        
        if (content.length == 0) {
            [SVProgressHUD showErrorWithStatus:@"回复内容不能为空"];
            return;
        }
        if ([astr isEqualToString:@"："]) {
            [tempComment reBackThis:content callback:^(NSString *err ,TYCommment *nowcoment) {
                if (!err) {
                    if(!lastTime)
                        lastTime = nowcoment.mTimeC;
                    firstTime = nowcoment.mTimeC;
                    [self.tableview reloadData];
                    
                    self.thePublish.mReBackCount++;
                    
                    coutlabel.text = self.thePublish.mReBackCount!=0? [NSString stringWithFormat:@"%d条回复",self.thePublish.mReBackCount]:@"暂无回复";
                    [self reloaTableView:nowcoment];
                    
                    [SVProgressHUD showSuccessWithStatus:@"回复成功"];
                    inputText.text = @"";
                    [inputText resignFirstResponder];
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:@"回复失败"];
                }
            }];
        }
    }

    else
    {
    [self.thePublish commentThis:inputText.text tagUser:self.thePublish.mTaguser.mObjId coordnate:[GInfo shareClient].mNowUserPoint  callback:^(NSString *err,TYCommment *comment) {
        if (!err) {
            [SVProgressHUD showSuccessWithStatus:@"回复成功"];
            self.thePublish.mReBackCount++;
            firstTime = comment.mTimeC;
            if(!lastTime)
                lastTime = comment.mTimeC;
            coutlabel.text = self.thePublish.mReBackCount!=0? [NSString stringWithFormat:@"%d条回复",self.thePublish.mReBackCount]:@"暂无回复";
            [self reloaTableView:comment];
            inputText.text = @"";
            [inputText resignFirstResponder];
            
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"回复失败"];
        }
    }];
    }
}


-(void)reloaTableView :(TYCommment *)comment
{
    
    
 //   [dataArray removeObjectAtIndex:1];

    [replyArray insertObject:comment atIndex:0];
    [self.tableview beginUpdates];
 

    NSIndexPath *insertIndex = [NSIndexPath indexPathForRow:0 inSection:0];
    NSArray * insertarray = [[NSArray alloc]initWithObjects:insertIndex, nil];
    [self.tableview insertRowsAtIndexPaths:insertarray withRowAnimation:UITableViewRowAnimationTop];
    
    [self.tableview endUpdates];
    
}

-(void)backgroundTaped:(UIGestureRecognizer*)ges
{
    [inputText resignFirstResponder];

}
-(void)photoTouched:(UIButton *)sender
{
    NSMutableArray *photos = [[NSMutableArray alloc] init];
    MWPhoto *photo;
    

    for (int i = 0; i< self.thePublish.mImgArr.count; i++) {
        
        
        NSString *image = [self.thePublish.mImgArr objectAtIndex:i];
        NSURL *url = [NSURL URLWithString: [Util makeBigImgURL:image]];
        
        photo = [MWPhoto photoWithURL:url];
       // photo = [MWPhoto photoWithImage:];
        // photo.caption = @"Fireworks";
        [photos addObject:photo];
    }
    browser.hiddenTopBtn = NO;
    browser.delegate = self;
    browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = NO;
    browser.zoomPhotosToFill = YES;
   // browser.currentIndex = sender.tag - 10;
    [browser setCurrentPhotoIndex:sender.tag - 10];
    
    self.photos = photos;
    
    
    [self.navigationController pushViewController:browser animated:YES];

}

-(void)leftBtnTouched:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)rightBtnTouched:(id)sender
{
    CGRect aarect = shareView.frame;

    aarect.origin.y = DEVICE_Height;
    shareView.frame = aarect;
    [self.view addSubview:shareView];
    [UIView animateWithDuration:0.2 animations:^{
        if (!DeviceIsiPhone5()) {
            CGRect rect = shareView.frame;
            rect.origin.y = -70;
            shareView.frame = rect;

        }
        else
        {
            CGRect rect = shareView.frame;
            rect.origin.y = 0;
            shareView.frame = rect;
        }

    }];
    
}
#pragma mark - MWPhotoBrowserDelegate
- (BOOL)photoBrowser:(MWPhotoBrowser *)photoBrowser isPhotoSelectedAtIndex:(NSUInteger)index
{
    NSLog(@"%lu",(unsigned long)index);
    return YES;
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.thePublish.mImgArr.count;
}
- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected
{
    NSLog(@"%lu",(unsigned long)index);
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photos.count)
        return [_photos objectAtIndex:index];
    return nil;
}
#pragma TableviewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return replyArray.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CustomCellIdentifier = @"DynamicReplayCell";
    
    DynamicReplayCell *cell = (DynamicReplayCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
    
    BOOL isUsed = NO;
    if (!isUsed &&! cell) {
        UINib *nib = [UINib nibWithNibName:@"DynamicReplayCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:@"DynamicReplayCell"];
        isUsed = YES;
        cell = (DynamicReplayCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];

    }
    cell.myView.layer.borderWidth = 0.5;
    cell.myView.layer.borderColor = [ColorRGB(212, 212, 212)CGColor];

    TYCommment *comment = [replyArray objectAtIndex:indexPath.row];
    NSMutableString *astra;
    
    //[astra appendString:comment.mUserName];
    int length = comment.mUserName.length;
    NSMutableAttributedString *astr ;
    if ( comment.mTagUserName != nil) {
        

        astra = [[NSMutableString alloc]initWithFormat:@"@%@",comment.mUserName];


        NSString *aastr = [NSString stringWithFormat:@" 回复@%@：",comment.mTagUserName];
        [astra appendString:aastr];
        [astra appendString:comment.mText];
        astr = [[NSMutableAttributedString alloc]initWithString:astra];

        [astr addAttribute:NSForegroundColorAttributeName value:ColorRGB(205, 136, 52) range:NSMakeRange(0,length+1)];
        [astr addAttribute:NSForegroundColorAttributeName value:ColorRGB(205, 136, 52) range:NSMakeRange(length+4,comment.mTagUserName.length+1)];
    }
    else
    {
        astra = [[NSMutableString alloc]initWithFormat:@"@%@：",comment.mUserName];
        [astra appendString:comment.mText];
        astr = [[NSMutableAttributedString alloc]initWithString:astra];

        [astr addAttribute:NSForegroundColorAttributeName value:ColorRGB(205, 136, 52) range:NSMakeRange(0,length+1)];

    }
    [cell upDateCell:astra];

    
    cell.replyContent.attributedText = astr;

    cell.replayTime.text = [Util FormartTime:comment.mTimeC bfull:NO];
    
     //cell.selectionStyle = UITableViewCellSelectionStyleNone;
    // cell.textLabel.text = @"success";
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
    
}

- (void) changeContentViewPoint:(NSNotification *)notification{
    
 [self.tableview addGestureRecognizer:gesture];
    
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGFloat keyBoardEndY = value.CGRectValue.origin.y;  // 得到键盘弹出后的键盘视图所在y坐标
    
    NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // 添加移动动画，使视图跟随键盘移动
    [UIView animateWithDuration:duration.doubleValue animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationCurve:[curve intValue]];
        
        if (SystemIsiOS7()) {
             inputView.center = CGPointMake(inputView.center.x, keyBoardEndY  - inputView.bounds.size.height/2.0);
        }
        else
        {
             inputView.center = CGPointMake(inputView.center.x, keyBoardEndY  - inputView.bounds.size.height/2.0-20);
        }
      //  inputView.center = CGPointMake(inputView.center.x, keyBoardEndY  - inputView.bounds.size.height/2.0);   // keyBoardEndY的坐标包括了状态栏的高度，要减去
        
    }];
}

-(void)keyboardWillHide:(NSNotification *)notification
{

  [self.tableview removeGestureRecognizer:gesture];
    NSDictionary *userInfo = [notification userInfo];
    NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    [UIView animateWithDuration:duration.doubleValue animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationCurve:[curve intValue]];
        if (SystemIsiOS7()) {
            inputView.center = CGPointMake(inputView.center.x, DEVICE_Height-inputView.frame.size.height/2);   // keyBoardEndY的坐标包括了状态栏的高度，要减去
        }
        else
        {
             inputView.center = CGPointMake(inputView.center.x, DEVICE_Height-inputView.frame.size.height/2-20);   // ke
        }
    }];
    
}
-(void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
//    [self.thePublish getComment:1 callback:^(NSArray *arr, NSString *err) {
//        if (arr&&!err) {
//            replyArray = [[NSMutableArray alloc]init];
//            [self.slimeView endRefresh];
//            [replyArray addObjectsFromArray:arr];
//            [self.tableview reloadData];
//        }
//        else
//        {
//            [SVProgressHUD showErrorWithStatus:@"获取评论失败"];
//        }
//    }];
    [self.thePublish getCommentByTime:firstTime bback:YES callback:^(NSArray *arr, NSString *err) {
        [self.slimeView endRefresh];
        [refresh stopAnimating];
        if (arr&&!err) {
            if (arr.count ==0) {
                [self.tableview reloadData];
                self.refreshLabel.text = self.textNoMore;
                
                return ;
            }
            TYCommment *state = [arr firstObject];
            firstTime = state.mTimeC;
            state = [arr lastObject];
            lastTime = state.mTimeC;
            
            NSRange range = NSMakeRange(0, [arr count]);
            [replyArray insertObjects:arr atIndexes: [NSIndexSet indexSetWithIndexesInRange:range]];

            [replyArray addObjectsFromArray:arr];
            [self.tableview reloadData];
            
            if (arr.count<ONE_PAGE) {
                self.refreshLabel.text = self.textNoMore;
            }
            else
            {
                self.refreshLabel.text = self.textPull;
                
            }
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"获取评论失败"];
        }
    }];

}

-(void)refresh
{
    [self.thePublish getCommentByTime:lastTime bback:NO callback:^(NSArray *arr, NSString *err) {
            [self stopLoading];
        if (arr&&!err) {
            if (arr.count ==0) {
             //   [SVProgressHUD showErrorWithStatus:@"没有更多评论"];
                   self.refreshLabel.text = self.textNoMore;
                [self.tableview reloadData];

                return ;
            }
            TYCommment *state = [arr firstObject];
            
            firstTime = state.mTimeC;
            state = [arr lastObject];
            lastTime = state.mTimeC;
            
            NSRange range = NSMakeRange(replyArray.count, [arr count]);
            [replyArray insertObjects:arr atIndexes: [NSIndexSet indexSetWithIndexesInRange:range]];
            [self.tableview reloadData];
            if (arr.count <ONE_PAGE) {
                self.refreshLabel.text = self.textNoMore;
            }
            else
            {
                self.refreshLabel.text = self.textPull;

            }
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"获取评论失败"];
        }
    }];

}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [inputText becomeFirstResponder];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TYCommment *coment = [replyArray objectAtIndex:indexPath.row];
    inputText.text = [NSString stringWithFormat:@"回复@%@：",coment.mUserName];
    TagNameStr  = coment.mUserName;
    tempComment = coment;
//    [coment reBackThis:@"" callback:<#^(NSString *err)callback#>]
    
}


//- (NSUInteger)supportedInterfaceOrientations
//{
//    return UIInterfaceOrientationPortrait;
//}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
